package com.xqls.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;

import com.xqls.dal.dao.TScheduleJobDao;
import com.xqls.dal.model.TScheduleJob;


public class QuatzService implements ApplicationListener<ContextRefreshedEvent>{
	public final Logger log = Logger.getLogger(this.getClass());
    @Autowired  
    private SchedulerFactoryBean schedulerFactoryBean;  
    @Autowired  
    private TScheduleJobDao TScheduleJobDao; 
    
    public void getInit() throws Exception {
    	//TODO 通过任务名  获得数据库表中的任务数据
    	List<TScheduleJob> jobList = TScheduleJobDao.selectAllJob();
    	if(jobList!=null && jobList.size()>0){
    	for (TScheduleJob tScheduleJob : jobList) {
    		addJob(tScheduleJob); 
    		tScheduleJob.setfIsConcurrent("yes");
    		TScheduleJobDao.updateJob(tScheduleJob);
		}}
    }
    
    public void addJob(TScheduleJob job) throws SchedulerException {  
  
        Scheduler scheduler = schedulerFactoryBean.getScheduler();  
        //StringUtils.isBlank判断某字符串是否为空或长度为0或由空白符(whitespace)构成
        String jobGroup = StringUtils.isBlank(job.getfJobGroup()) ? Scheduler.DEFAULT_GROUP  
                : job.getfJobGroup();  
        //triggerJob主要是用于执行一次任务的场景，传入jobKey即可启动该任务
        TriggerKey triggerKey = TriggerKey.triggerKey(job.getfJobName(),  
                jobGroup);  
      //获取trigger，即在spring配置文件中定义的 bean id="myTrigger"
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);  
        // 不存在，创建一个  
        if (null == trigger) {  
        	//JobDetail – 定义Job的实例；
            JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class)  
                    .withIdentity(job.getfJobName(), jobGroup).build();  
  
            jobDetail.getJobDataMap().put("scheduleJob", job);  
  
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder  
                    .cronSchedule(job.getfCronExpression());  
            //调度触发器
            trigger = TriggerBuilder.newTrigger()  
                    .withIdentity(job.getfJobName(), jobGroup)  
                    .withSchedule(scheduleBuilder).build();  
            //Trigger – 触发Job的执行；
            //调度工厂
            scheduler.scheduleJob(jobDetail, trigger);  
        } else {  
            // Trigger已存在，那么更新相应的定时设置  
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder  
                    .cronSchedule(job.getfCronExpression());  
  
            // 按新的cronExpression表达式重新构建trigger  
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)  
                    .withSchedule(scheduleBuilder).build();  
  
            // 按新的trigger重新设置job执行  
            scheduler.rescheduleJob(triggerKey, trigger);  
        }  
    }  
    
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		try {  
			if(event == null){
            getInit();  
			}
        } catch (Exception e) {  
            log.error("触发器任务异常",e);
        }  
		
	}

}
